package com.hx.er.common.logic;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

import net.sf.json.JSONArray;

import com.hx.er.common.entity.ErBehaviorEntity;
import com.hx.er.common.system.Constants;
import com.hx.er.common.system.ErProperties;
import com.hx.er.common.util.FileUtil;

public class BehaviorManager {
	private static BehaviorManager behaviorManager;
	private static List<ErBehaviorEntity> behaviorList = new LinkedList<ErBehaviorEntity>();
	private static final int LIST_SIZE = Integer.parseInt(ErProperties.getProperty(Constants.PROPERTY_BEHAVIOR_TEMP_LIST_SIZE));
	private static final String TEMP_PATH = ErProperties.getProperty(Constants.PROPERTY_BEHAVIOR_TEMP_FILE_PATH);

	public synchronized static BehaviorManager getInstance() {
		if (behaviorManager == null) {
			behaviorManager = new BehaviorManager();
		}

		return behaviorManager;
	}

	public synchronized void append(ErBehaviorEntity behavior) {
		if (behaviorList.size() < LIST_SIZE) {
			behaviorList.add(behavior);
		} else {
			List<ErBehaviorEntity> behaviorListTemp = behaviorList;
			behaviorList = new LinkedList<ErBehaviorEntity>();

			Thread newThread = new FileOutputThread(behaviorListTemp);
			newThread.start();
		}
	}

	public class FileOutputThread extends Thread {
		List<ErBehaviorEntity> behaviorListTemp;

		public FileOutputThread(List<ErBehaviorEntity> behaviorListTemp) {
			this.behaviorListTemp = behaviorListTemp;
		}

		@Override
		public void start() {
			long timeStamp = System.currentTimeMillis();
			File tempPath = new File(TEMP_PATH + timeStamp + ".txt");
			FileUtil.createDir(tempPath);

			StringBuilder sb = new StringBuilder();
			for (ErBehaviorEntity eachBehavior : behaviorListTemp) {
				JSONArray jsonArray = JSONArray.fromObject(eachBehavior);
				sb.append(jsonArray.toString());
				sb.append("\r\n");
			}

			FileOutputStream fos = null;
			try {
				tempPath.createNewFile();
				fos = new FileOutputStream(tempPath);
				fos.write(sb.toString().getBytes());
				fos.flush();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if (fos != null) {
					try {
						fos.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}
}
